package com.hanyao.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.hanyao.reggie.common.BaseContext;
import com.hanyao.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 寒钥
 * @version 1.0
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter{
    private static final AntPathMatcher ANTPATHMATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String requestURI = request.getRequestURI();
        Long id = (Long)request.getSession().getAttribute("id");
        Long user = (Long)request.getSession().getAttribute("user");
        //BaseContext.setCurrentId(id);
        String[] uris = new String[]{
          "/backend/**",
          "/front/**",
          "/employee/login",
          "/employee/logout", "/user/sendMsg","/user/login","/druid/*"
        };
        if(check(uris,requestURI)){
            log.info("本次请求{}不需要拦截",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        //判断员工登录
        if(id != null){
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request,response);
            return;
        }
        //判断移动端客户登录
        if(user != null){
            BaseContext.setCurrentId(user);
            filterChain.doFilter(request,response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    private boolean check (String[]urls,String requestURI){
        for (String url : urls) {
            if(ANTPATHMATCHER.match(url,requestURI)){
                return true;
            }
        }
        return false;
    }
}
